var netWork = require('../../../utils/netWork.js');
var apiCode = require('../../../utils/openApiCode.js');
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const log = require('../../../utils/logs.js');
const app = getApp();
var isClick = true;
import {authUserPhone} from "../../../utils/publicMethods";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topHeight: 0, //顶部高度
    imagesUrl: getApp().globalData.imagesUrl,
    ani: 0, //动画是否执行
    prizeIntegration: 0, //中奖积分
    isShowModalRule: false, //是否显示活动规则
    isShowModalAuth: false, //是否显示授权按钮
    isShowModalPubNum: false, //顶部关注公众号
    isFollow: 1, // 0-未关注，1-已关注
    isSetting: 0,
    isShowMask: false, //关注公众号的阴影
    getPhone: false, //是否已拉取手机号
    officialHeight: 0 //顶部关注公众号的高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    api.showLoading('正在加载中...');
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    if (wx.getStorageSync('getPhone')) {
      this.setData({
        getPhone: wx.getStorageSync('getPhone'),
      })
    }
    this.setData({
      topHeight: topHeight,
      source: options.source //兑奖来源
    });
    let prizeList = wx.getStorageSync('prizeList');
    let prizeIntegration = options.source == "2" ? options.prizeIntegration : prizeList.prizeIntegration;
    let prizeOrderId = options.source == "2" ? options.prizeOrderId : prizeList.prizeOrderId;
    let prizeId = options.source == "2" ? options.prizeId : prizeList.prizeId;
    this.setData({
      prizeIntegration: prizeIntegration,
      prizeOrderId: prizeOrderId,
      prizeId: prizeId
    })
    // 获取jsCode
    this.updateJSCode();
    // 获取是否关注公众号
    //this.queryIsFollow();
    // 获取积分
    this.queryIsSendPoint();
  },
  /**
   * 获取积分
   */
  queryIsSendPoint() {
    const that = this;
    netWork.POST('xhtx/little/sendPoint', {
      data: {
        prizeOrderId: that.data.prizeOrderId
      },
      success: function (res) {
        if (res.data.retCode == undefined) {

        } else {
          if (res.data.retCode == "0000") {
            if (res.data.point != null && res.data.point != 0) {
              that.setData({
                point: res.data.point
              })
            }
          }
        }
      },
      fail: function () {

      }
    });
  },
  /**
   *查询是否关注公众号
   */
  queryIsFollow: function () {
    const that = this;
    netWork.POST('searchUserInfo', {
      data: {
        userId: wx.getStorageSync('userId')
      },
      success: function (res) {
        api.cancelLoading();
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          if (res.data.data.isFollow == 1) {
            that.setData({
              isFollow: res.data.data.isFollow,
            })
          }
          if (res.data.data.activityId != null && res.data.data.activityId != "") {
            wx.setStorageSync('userType', "2");
          }
        }
      },
      fail: function () {
        wx.redirectTo({
          url: '../../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
        })
      }
    });
  },
  updateJSCode() {
    wx.login({
      success: res => {
        console.log("[onLoad--wx.login]" + res.code);
        if (res.code) {
          wx.setStorageSync('code', res.code)
        } else {
          console.log("获取jsCode失败" + res.errMsg);
        }
      }
    });
  },
  /**
   * 显示活动规则
   */
  showRule: function () {
    console.log('show')
    this.setData({
      isShowModalRule: true,
      ani: 0
    })
  },
  /**
   * 关闭活动规则
   */
  clickClose: function () {
    this.setData({
      ani: 1
    })
    const that = this;
    setTimeout(function () {
      that.setData({
        isShowModalRule: false
      })
    }, 180);
  },
  /**
   * 点击领取,进行兑奖
   */
  revicePrize: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    //防止重复点击或者点击过快
    console.log("点击了");
    if(!isClick){
      console.log("重复返回~");
      return;
    }
    if(isClick) {
      isClick = false;     
      //定时器
      setTimeout(function() {
        isClick = true;
      }, 5000);//3秒内不能重复点击
    }
    const that = this;
    api.showLoading('正在领取...')
    //积分兑奖
    netWork.POST('xhtx/little/receiveIntegral', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: that.data.prizeOrderId,
        prizeId: that.data.prizeId,
        positioningStyle: wx.getStorageSync('positioningStyle') == '' ? '0' : wx.getStorageSync('positioningStyle'),
        positioningType: wx.getStorageSync('positioningType') == '' ? '-1' : wx.getStorageSync('positioningType'),
        latitude: wx.getStorageSync('latitude'),
        longitude: wx.getStorageSync('longitude'),
        speed: wx.getStorageSync('speed'),
        accuracy: wx.getStorageSync('accuracy'),
        source: that.data.source, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
      },
      success: function (res) {
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          wx.redirectTo({ //跳转到 领取成功页面
            url: '../../success/success?c=&prizeOrderId='+that.data.prizeOrderId
          })
        } else {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          })
        }

      },
      fail: function () {
        wx.redirectTo({
          url: '../../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
        })
      }
    });



  },
  /**
   *查询是否关注公众号
   */
  queryIsFollow: function () {
    const that = this;
    netWork.POST('searchUserInfo', {
      data: {
        userId: wx.getStorageSync('userId')
      },
      success: function (res) {
        api.cancelLoading();
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          if (res.data.data.isFollow == 1) {//关注
            //跳转中奖记录
            wx.redirectTo({
              url: '../../prizeRecord/prizeRecord',
            })
          } else {//未关注，引导关注
            wx.navigateTo({
              url: '../../officialAccount/officialAccount',
            })
          }
          
        }else{//失败，暂时不按未关注处理

        }
      },
      fail: function () {
        // wx.redirectTo({
        //   url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        // })
      }
    });
  },
  /**
   * 跳转中奖记录页面
   */
  showPrizeRecord: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    // this.queryIsFollow();
  },
  /**
   * 更多活动， 跳转第三方小程序
   */
  showMore: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    wx.navigateToMiniProgram({
      appId: api.thirdAppId,
    })
  },
  closeMask: function () {
    console.log('closeMaks')
    this.setData({
      isShowModalRule: false, //是否显示活动规则
      isShowModalPubNum: false, //顶部关注公众号
    })
    if (!this.data.isShowModalAuth) {
      this.revicePrize(); //兑奖
    }
  },

  officialLoad: function (e) {
    //加载成功，阴影和动画出现
    this.setData({
      isShowMask: true
    })
  },
  officialError: function (e) {
    api.showLoading('正在领奖...')
    //场景错误，进行兑奖
    this.revicePrize();
  },
  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber: async function (e) {
    api.showLoading('正在获取信息...');
    var that = this;
    if (e.detail.encryptedData != undefined) {
      that.setData({ //同意
        isShowModalAuth: false
      })
      wx.setStorageSync('getPhone', true)
      that.setData({
        getPhone: true
      })
      console.log('手机号====' + JSON.stringify(e.detail))
      if (wx.getStorageSync('getLocationStyle') == "prize") { //兑奖时时拉取
        this.getLoca();
      } else {
        if (that.data.isFollow == 0) { //未关注，引导关注
          //展示关注公众号组件
          that.setData({
            isShowModalPubNum: true
          })
        } else {
          this.revicePrize();
        }
      }
      //更新用户信息
      let res = await authUserPhone(e);
    } else {
      api.cancelLoading();
      that.setData({ //显示拒绝授权提示层
        isShowModalAuth: true,
        authText:"为了保证正常获取奖励，现需获取您的手机号码",
        isPhone: '1'
      })
    }
  },
  /**
   * 点击领取
   */
  onclickrevicePrize() {
    if (this._freshing) return
    this._freshing = true;
    api.showLoading('正在领取...')
    if (wx.getStorageSync('getLocationStyle') == "prize") { //兑奖时时拉取
      this.getLoca();
      this._freshing = false;
    } else {
      if (this.data.isFollow == 0) { //未关注，引导关注
        //展示关注公众号组件
        this.setData({
          isShowModalPubNum: true
        })
      } else {
        this.revicePrize();
      }
      this._freshing = false;
    }
  },
  //获取用户地理位置，然后进行兑奖
  getLoca: function () {
    api.showLoading('正在获取位置...')
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        //存入地址
        wx.setStorageSync('latitude', res.latitude);
        wx.setStorageSync('longitude', res.longitude);
        wx.setStorageSync('speed', res.speed);
        wx.setStorageSync('accuracy', res.accuracy);
        if (that.data.isFollow == 0) { //未关注，引导关注
          //展示关注公众号组件
          that.setData({
            isShowModalPubNum: true
          })
        } else {
          this.revicePrize();
        }
        //兑奖
      },
      fail: res => {
        console.log('[wx.getLocation===res.errMsg]' + JSON.stringify(res.errMsg))
        api.cancelLoading();
        if (res.errMsg) {
          that.setData({
            isShowModalAuth: true,
            authText:"为了保证正常获取奖励，现需获取您的地理位置",
            isSetting: 1
          })
        }
      }
    })
  },
  /**
   * 更新用户信息
   */
  updateUserInfo(encryptedData, iv) {
    const that = this;
    netWork.POST('updateUserInfo', {
      data: {
        userId: wx.getStorageSync('userId'),
        encryptedData: encodeURIComponent(encryptedData),
        iv: encodeURIComponent(iv),
        jsCode: wx.getStorageSync('code')
      },
      success: function (res) {
        if (res.data.retCode == undefined) {
          // wx.redirectTo({
          //   url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          // })
        }
        if (res.data.retCode == '0000') {
          wx.setStorageSync('userPhone', res.data.data.phone);
          wx.setStorageSync('nickName', res.data.data.nickName);
        } else {
          //跳转温馨提示页面
          // wx.redirectTo({
          //   url: '../../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          // })
        }
      },
      fail: function (res) {
        //跳转温馨提示页面
        // wx.redirectTo({
        //   url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        // })
      }
    });
  },
  openSetting() {
    this.setData({
      isShowModalAuth: false
    })
    api.putOpenSetting();
  },
  /**
   * 关闭积分
   */
  closePoint: function () {
    this.setData({
      point: null
    })
  },
  onShow(){
    try {
        if (wx.onNeedPrivacyAuthorization) {
            wx.onNeedPrivacyAuthorization(resolve => {
                this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                this.resolvePrivacyAuthorization = resolve
            })
        }
    } catch (error) {
        console.info(error)
    }
  }
})